<template>
    <div>
        <el-form class="" inline :model="selectfrom" label-width="auto">
            <el-form-item label="名称">
                <el-input v-model="like" clearable></el-input>
            </el-form-item>
            <el-form-item label="ID">
                <el-input v-model="selectfrom.ID" clearable></el-input>
            </el-form-item>
            <el-form-item label="来源">
                <el-input v-model="selectfrom.dataform" clearable></el-input>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="selectfrom.info" clearable></el-input>
            </el-form-item>
            <el-form-item label="内存大小">
                <el-input v-model="selectfrom.memorylimit" clearable></el-input>
            </el-form-item>
            <el-form-item label="时间大小">
                <el-input v-model="selectfrom.timelimit" clearable></el-input>
            </el-form-item>
            <el-form-item label="公开类型">
                <el-select v-model="selectfrom.range" placeholder="请选择公开类型" clearable style="width: 177px">
                    <el-option label="公开" value="public"></el-option>
                    <el-option label="团队" value="team"></el-option>
                    <el-option label="个人" value="user"></el-option>
                    <el-option label="精选" value="match"></el-option>
                    <el-option label="Accoders" value="accoder"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="题目类型">
                <el-select v-model="selectfrom.type" placeholder="请选择题目类型" clearable style="width: 177px">
                    <el-option label="代码" value="代码"></el-option>
                    <el-option label="单选" value="单选"></el-option>
                    <el-option label="判断" value="判断"></el-option>
                    <el-option label="多选" value="多选"></el-option>
                    <el-option label="填空" value="填空"></el-option>
                    <el-option label="拍照" value="拍照"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="标签">
                <el-cascader placeholder="标签" v-model="setlabel" :options="grouplabel" filterable :props="{
                    checkStrictly: true,
                    value: 'ID',
                    label: 'name',
                }" clearable style="width: 177px" />
            </el-form-item>
            <el-form-item label="团队id">
                <el-input v-model="selectfrom.teamid" clearable></el-input>
            </el-form-item>
            <el-form-item label="用户id">
                <el-input v-model="selectfrom.userid" clearable></el-input>
            </el-form-item>
            <el-form-item label="排序">
                <el-select v-model="order" placeholder="排序" style="width:120px">
                    <el-option label="名称" value="name"></el-option>
                    <el-option label="ID" value="ID"></el-option>
                    <el-option label="来源" value="dataform"></el-option>
                    <el-option label="备注" value="info"></el-option>
                    <el-option label="公开类型" value="range"></el-option>
                    <el-option label="测试点数量" value="testcases.questionid"></el-option>
                    <el-option label="题解数量" value="accepted.questionid"></el-option>
                </el-select>
                <el-select v-model="sortable" placeholder="排序" style="width: 80px">
                    <el-option label="降序" value="DESC"></el-option>
                    <el-option label="升序" value="ASC"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button-group>
                    <el-button @click="start" type="primary" :icon="Search"> 查询 </el-button>
                    <el-button @click="clearable" type="primary"> 清空 </el-button>
                    <router-link v-slot="{ navigate }" custom :to="{ name: '批量导入题目' }">
                        <el-button @click="navigate" type="primary">+批量导入</el-button>
                    </router-link>
                    <router-link v-slot="{ navigate }" custom :to="{ name: '更新题目' }">
                        <el-button @click="navigate" type="primary">+添加题目</el-button>
                    </router-link>
                    <AILabel v-if="!tenant_id"></AILabel>
                </el-button-group>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" border height="69vh" @sort-change="sortchange">
            <el-table-column v-if="ischecked" label="选择" width="50px">
                <template #default="scope">
                    <input type="checkbox" :value="scope.row.ID" class="form-check-input" v-model="checkedNames" />
                </template>
            </el-table-column>
            <el-table-column prop="ID" sortable="custom" width="80" label="ID"></el-table-column>
            <el-table-column prop="name" label="name" width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="type" sortable="custom" label="类型" width="80"></el-table-column>
            <el-table-column prop="range" sortable="custom" label="公开类型" width="110px">
                <template #default="{ row }">
                    <el-tooltip v-if="row.range === 'user'" placement="top">
                        <template #content>
                            {{ `${row?.user?.ID} - ${row?.user?.name}` }}
                        </template>
                        <el-tag class="cu" type="primary">{{range.find(c => c.value === row.range)?.label}}</el-tag>
                    </el-tooltip>
                    <el-tag type="primary" v-else>{{range.find(c => c.value === row.range)?.label}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="difficulty" sortable="custom" label="难度" width="110">
                <template #default="{ row }">
                    <div v-if="row.difficulty" :class="`difficulty-${row.difficulty}`">
                        {{ row.difficulty ? store.state.state?.difficulty[row.difficulty] : '' }}
                    </div>
                </template>
            </el-table-column>
            <!-- <el-table-column
        prop="knowledgepoints"
        :formatter="(s) => atSting(s.knowledgepoints)"
        label="知识点"
        ></el-table-column>-->
            <el-table-column prop="label" label="知识点" width="" show-overflow-tooltip
                :tooltip-formatter="({ row, column, cellValue }) => row.questionlabel.map((vo: { labelid: number | undefined; }) => getlabel.find(e => e.ID === vo.labelid)?.name).join(', ')">
                <template #default="{ row }">
                    <el-tag class="question-intable-label" text type="primary" effect="plain" size="default"
                        v-for="(v, key) in row.questionlabel" :key="`1-${key}`">
                        {{getlabel.find(e => e.ID === v.labelid)?.name}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="ailabel" label="标签(AI)" width="" show-overflow-tooltip>
                <template #default="{ row }">
                    <el-tag class="question-intable-label" text type="primary" effect="plain" size="default"
                        v-for="(v, index) in row.ailabel" :key="`${v}-${index}`">
                        {{ v }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="dataform" label="来源" width="80px"></el-table-column>
            <el-table-column prop="info" label="备注" width="80px"></el-table-column>
            <el-table-column prop="updatedAt" width="120px" sortable="custom" :formatter="formatter"
                label="更新时间"></el-table-column>
            <el-table-column prop="testcaseslength" label="测试点" width="70">
                <template #default="scope">
                    <router-link :to="{ name: '测试点', params: { ID: scope.row.ID } }">{{ scope.row.testcaseslength
                        }}</router-link>
                </template>
            </el-table-column>
            <el-table-column prop="acceptedlength" label="题解" width="60">
                <template #default="scope">
                    <router-link :to="{ name: '题解', params: { ID: scope.row.ID } }">{{ scope.row.acceptedlength
                        }}</router-link>
                </template>
            </el-table-column>
            <el-table-column prop="userquestionlength" label="答题" width="60"></el-table-column>
            <el-table-column label="操作" fixed="right" width="230">
                <template #default="scope">
                    <router-link v-slot="{ navigate }" custom :to="{ name: '题目', params: { ID: scope.row.ID } }">
                        <el-button @click="navigate" type="info">查看</el-button>
                    </router-link>
                    <router-link v-slot="{ navigate }" custom :to="{ name: '更新题目', query: { ID: scope.row.ID } }">
                        <el-button @click="navigate" type="warning">修改</el-button>
                    </router-link>
                    <el-button v-if="!tenant_id" @click="del(scope.row.ID)" type="danger">删除</el-button>
                    <!-- <el-button
              size="default"
              @click="changelabel(scope.row.ID, scope.row.name)"
            >答题记录({{ scope.row.userquestionlength }})</el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="pager" :page-size="Number(limit)" :total="count" :page-sizes="pageSizes"
            layout="total,sizes,prev, pager, next" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
        </el-pagination>
    </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElButton, ElInput, ElMessage, ElMessageBox, ElOption, ElPagination, ElSelect, ElTable, ElTableColumn } from "element-plus";
import { forEach } from "lodash-es";
import { flatten } from "underscore";
import { computed, inject, onMounted, reactive, ref, watch, } from "vue";
import { useStore } from "vuex";
import { Iobj, asyncdelquestion } from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { findpid } from "../../../util/code";
import { toLocaleDateString } from "../../../util/time";
import AILabel from "./components/AILabel.vue";
// 码客行
const tenant_id = inject<string | undefined>('tenant_id', undefined)

const range = [
    { label: "公开", value: "public" },
    { label: "团队", value: "team" },
    { label: "个人", value: "user" },
    { label: "精选", value: "match" },
    { label: "codeforces", value: "codeforces" },
    { label: "Accoders", value: "accoder" },
]

const prop = defineProps<{
    ischecked?: boolean,
    list?: number[],
    changelabel?: Function,
    tablekey?: Array<keyof Studycodemodel.Iquestion>,
    handleSelectionChange?: (n: Studycodemodel.Iuser[]) => void,
    selectarr?: number[],
    userhandleCurrentChange?: (n: Studycodemodel.Iuser) => void,
    where?: Studycodemodel.Iquestion,
    team?: Studycodemodel.Iteam,
    user?: Studycodemodel.Iuser,
    teamid?: number
}>()

const sortable = ref<"DESC" | "ASC">("DESC");
const offset = ref(0);
const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500]
const order = ref<keyof Studycodemodel.Iquestion>("ID");
const like = ref("");
const select = ref<keyof Studycodemodel.Iquestion>('ID')
const query = computed(() => {
    let _like: [keyof Studycodemodel.Iquestion, string | number] | undefined;
    const obj: Iobj<Studycodemodel.Iquestion> = {
        _limit: Number(limit.value),
        _offset: Number(offset.value),
        _order: order.value,
        _sortable: sortable.value,
    };
    if (prop.teamid) {
        obj.teamid = prop.teamid
    }
    if (like.value) {
        _like = ['name', like.value];
    }
    const { info, ...w } = selectfrom;
    Object.assign(obj, w)

    if (info) {
        if (!_like) {
            _like = ["info", info];
        } else {
            obj.info = info;
        }
    }
    if (_like) {
        obj._like = _like;
    }

    if (setlabel.value && setlabel.value.length) {
        const n = setlabel.value[setlabel.value?.length - 1]
        const data = store.state.label?.rows.filter(
            (e) => e.type === "题目标签"
        );
        const questionlabel = flatten(findpid(data ? data : [], n)).map(
            (e) => e.ID
        );
        if (!obj._include) obj._include = {};
        obj._include.questionlabel = ["labelid", questionlabel.concat(n)];
    }
    return obj;
});
const selectfrom = reactive<Studycodemodel.Iquestion>({
    dataform: "",
    info: "",
    type: undefined,
});
const checkedNames = ref<number[]>([]);
const store = useStore(Storekey);
const IID = ref<number | boolean>();
const setlabel = ref<number[]>([]);

const tableData = computed<Studycodemodel.Iquestion[]>(() => {
    return store.getters.getquestion;
});

const getlabel = computed(() => {
    return store.state.label?.rows || [];
});

const count = computed<number>(() => {
    return store.getters.getquestioncount;
});

onMounted(() => {
    if (prop.list) {
        checkedNames.value = prop.list;
    }
    store.dispatch("actionlabel");
    start();
});

const grouplabel = computed(() => {
    const data = store.state.label?.rows.filter((e) => e.type === "题目标签");
    return findpid(data ? data : []);
});

async function start() {
    try {
        store.dispatch("actionquestion", query.value);
    } catch (e: any) {
        console.log(e);
        ElMessage.error(e);
    }
}

function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
}
const handleSizeChange = (val: number) => {
    limit.value = val
    start()
}
function sortchange(row: {
    order: string;
    prop: keyof Studycodemodel.Iquestion;
}) {
    const { prop } = row;
    if (row.order == "descending") {
        sortable.value = "DESC";
    } else {
        sortable.value = "ASC";
    }
    order.value = prop;
}

function formatter({ updatedAt }: Studycodemodel.Iquestion) {
    return toLocaleDateString(updatedAt);
}

function del(ID: number) {
    ElMessageBox.confirm("是否删除该选项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            await asyncdelquestion({ ID });
            ElMessage({
                type: "success",
                message: "删除成功!",
            });
            start();
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "已取消删除",
            });
        });
}

function clearable() {
    forEach(selectfrom, (e, k) => {
        delete selectfrom[k]
    })
    setlabel.value = []
}

watch([limit, offset, order, sortable], () => {
    start();
});

</script>

<style scoped>
a {
    text-decoration: none;
}
</style>

<style>
.admin-main {
    overflow: auto;
}

.admin-container {
    height: 100%;
}
</style>